package com.xxkj.drugtraceability.ui.departhd

import android.graphics.Typeface
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewParent
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.App
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.ActivityDepartDrugcollectionBinding
import com.xxkj.drugtraceability.databinding.ActivityDepartHdDrugcollectionBinding
import com.xxkj.drugtraceability.databinding.LayoutDepartCollectTopViewBinding
import com.xxkj.drugtraceability.databinding.LayoutDrupCollectTopViewBinding
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.utils.showCompleteToast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/12/02 11:43
 * description:病房发药采集
 */
class DepartDrugHdActivity:BaseVMActivity() {
    private val binding by binding<ActivityDepartHdDrugcollectionBinding>(R.layout.activity_depart_hd_drugcollection)
    private val viewModel by viewModel<DepartDrugHdCollectionViewModel>()
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            viewModel.mFragmentList.add(DepartDrugHdFragment.newInstance(0))
            viewModel.mFragmentList.add(DepartDrugHdFragment.newInstance(1))
            binding.viewPager.adapter = mAdapter
            viewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
                override fun onPageScrollStateChanged(state: Int) {

                }

                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    viewModel.viewpagerIndex.postValue(position)
                }
            })
            llWei.clickN {
                if (viewModel.viewpagerIndex.value!=0){
                    binding.viewPager.currentItem = 0
                }
            }
            llYi.clickN {
                if (viewModel.viewpagerIndex.value!=1){
                    binding.viewPager.currentItem = 1
                }
            }
            tvHd.clickN {
                var alert = false
                var noData = true
                var dataList = mutableListOf<DrugInfoReq>()
                var fylsh = ""
                var messageList = mutableListOf<DepartDrugInfo>()
                viewModel.dataList.value?.forEach {
                    if (it.isSync&&it.isCheck!="1"){
                        noData = false
                        if (it.hdNum.isNotEmpty()&&it.fysl?.toDouble()!=it.hdNum.toDouble()){
                            alert = true
                            messageList.add(it)
                        }
                        dataList.add(DrugInfoReq(it.hdNum,it.ydbh))
                        fylsh = it.fylsh
                    }
                    if(!it.isSync){
                        alert = true
                    }
                }
                viewModel.unDataList.value?.forEach {
                    if (it.isSync&&it.isCheck!="1"){
                        if (it.hdNum.isNotEmpty()&&it.fysl?.toDouble()!=it.hdNum.toDouble()){
                            alert = true
                            messageList.add(it)
                        }
                        noData = false
                        fylsh = it.fylsh
                        dataList.add(DrugInfoReq(it.hdNum,it.ydbh))
                    }
                    if(!it.isSync){
                        alert = true
                    }
                }
                if (noData){
                    //提示没有任何数据
                    YellowDialog(this@DepartDrugHdActivity,resources.getString(R.string.no_data),type = 1){

                    }
                }else{
                    if (alert){
                        if (messageList.size>0){
                            //数量不对，需要提醒
                            val buffer = StringBuffer()
                            buffer.append("<font color='#33333F'>")
                            buffer.append("发药单扫码数量与实际核对数量不一致:<br>")
                            buffer.append("</font>")
                            messageList.forEach {
                                buffer.append("<font color='#3C85FF'>")
                                buffer.append(it.mc)
                                buffer.append("</font>")
                                buffer.append("<font color='#33333F'>")
                                buffer.append("药品发药单数量为")
                                buffer.append("</font>")
                                buffer.append("<font color='#F7745C'>")
                                buffer.append(it.fysl)
                                buffer.append("</font>")
                                buffer.append("<font color='#33333F'>")
                                buffer.append("实际核对数量为")
                                buffer.append("</font>")
                                buffer.append("<font color='#F7745C'>")
                                buffer.append(it.hdNum+"<br>")
                                buffer.append("</font>")
                            }
                            BlueDialog(this@DepartDrugHdActivity,buffer.toString()){
//                                viewModel.finishScanDrugCode(DepartHdRequest(dataList,fylsh))
                            }
                        }else{
                            //有没有核对的，需要提醒
                            BlueDialog(this@DepartDrugHdActivity,resources.getString(R.string.scan_not_all)){
                                //保存数据
                                viewModel.finishScanDrugCode(DepartHdRequest(dataList,fylsh))
                            }
                        }

                    }else{
                        //保存数据
                        viewModel.finishScanDrugCode(DepartHdRequest(dataList,fylsh))
                    }
                }
            }
        }
    }

    override fun initData() {
    }

    override fun startObserve() {
        viewModel.departData.observe(this, Observer {
            if (it!=null){
                binding.sll.visibility = View.VISIBLE
                binding.viewPager.visibility = View.VISIBLE
                binding.tvName.text = it.bqmc
                binding.tvDate.text = "发药流水号：${it.fylsh}"
                if (!it.noEnterDrugInfoList.isNullOrEmpty()){
                    binding.llBottom.visibility = View.VISIBLE
                }else{
                    binding.llBottom.visibility = View.GONE
                }
            }else{
                try {
                    binding.viewPager.currentItem = 0
                    binding.sll.visibility = View.GONE
                    binding.viewPager.visibility = View.GONE
                    binding.llBottom.visibility=View.GONE
                } catch (e: Exception) {
                }
            }

        })
        viewModel.viewpagerIndex.observe(this, Observer {
            when(it){
                0->{
                    binding.svWei.visibility=View.VISIBLE
                    binding.tvWei.setTypeface(null, Typeface.BOLD) // 加粗
                    binding.tvYi.setTypeface(null, Typeface.NORMAL)
                    binding.svYi.visibility=View.INVISIBLE
                }
                1->{
                    binding.svWei.visibility=View.INVISIBLE
                    binding.svYi.visibility=View.VISIBLE
                    binding.tvWei.setTypeface(null, Typeface.NORMAL) // 加粗
                    binding.tvYi.setTypeface(null, Typeface.BOLD)
                }
            }
        })
        viewModel.baseUiModel.observe(this, Observer {
            if (it.showLoading){
                showMyDialog(resources.getString(R.string.getting_data))
            }else{
                dismissMyDialog()
            }
            if (!it.showError.isNullOrEmpty()){
                BlueDialog(this,it.showError!!,type = 1){}
            }
            if (it.showSuccess==true){
                showCompleteToast(this)
            }
        })

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@DepartDrugHdActivity)){
                        val barcodeMessage = this.any as BarcodeMessage
                        if (viewModel.Prescriptionbarcode.isEmpty()){
                            //无值扫的算处方码
                            viewModel.getPrescriptionInfo(barcodeMessage.barcode)
                        } /*else{
                            if(barcodeMessage.type== BarcodeType.SUYUAN){
                                if (viewModel.canAdd){
                                    //扫码去
                                    viewModel.trugTracCodgIsGather(barcodeMessage.barcode)
                                }
                            }else{
                                YellowDialog(this@DepartDrugHdActivity,resources.getString(R.string.scan_suyuan),type = 1){}
                            }

                        }*/
                    }
                }
            }
        }
    }
    private val mAdapter: FragmentPagerAdapter =
        object : FragmentPagerAdapter(supportFragmentManager) {
            override fun getCount(): Int {
                return viewModel.mFragmentList.size
            }

            override fun getItem(arg0: Int): Fragment {
                return viewModel.mFragmentList[arg0]
            }
        }
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}